<?php

namespace humhub\modules\api\controllers;

use humhub\modules\content\models\Content;
use Yii;
use yii\web\HttpException;
use humhub\modules\space\models\Membership;
use humhub\modules\api\models\Task;
use humhub\modules\api\models\TaskUser;
use humhub\modules\post\models\Post;
use humhub\modules\api\models\User;
#use humhub\modules\api\models\Space;
use humhub\modules\space\models\Space;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 任务（task）相关接口
 * , 删除任务(post)请参考Content接口
 */
class TaskController extends Base2Controller
{

    /**
     * @inheritdoc
     */
    public $hideSidebar = true;

    /**
     * @inheritdoc
     */
    public function init(){
        $cClass = \Yii::$app->request->post('containerClass');
        if( $cClass == 'space' ){
            $_GET['sguid'] = \Yii::$app->request->post('containerGuid');
            $_POST['containerClass'] = 'humhub\modules\space\models\Space';
        }
        //stream
        if( isset($_GET['s']) ){
            $_GET['sguid'] = Yii::$app->request->get('s');
        }

        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];
        return $behaviors;
    }

    /**
     * 发布子任务
     *
     * POST /api/task
     *
     * post.containerClass 发布类型，[=space]发布到space
     *
     * post.containerGuid  类型GUID，其值为别为space或user的guid
     *
     * post.message        发布的内容
     *
     * post.visibility     [=1]公共, [=0]默认私有
     *
     * post.fileList       上传文件，值为文件的guid，每个guid需以逗号[,]开头
     *
     * post.notifyUserInput 通知(Notify)用户，值为用户的guid，每个guid需以逗号[,]结尾
     *
     * post.p_type 发布的post类型：=1任务
     *
     * post.p_title 发布的任务标题
     *
     * post.p_team  任务类型(=0个人任务，=1团队任务)
     *
     * post.p_score 子任务的积分奖励
     *
     * post.p_video 新增视频上传
     *
     * post.ry_did 融云讨论组id
     *
     * @return array 新post(子任务)的id信息
     */
    public function actionCreate(){
        $cClass = \Yii::$app->request->post('containerClass');
        $p_type = \Yii::$app->request->post('p_type');
        //1=任务  2=课程
        if( $cClass == 'space' ){
            if( $p_type == 1 ){
                //check : task
            }else{
                throw new \yii\web\BadRequestHttpException('p_type error.');
            }
        }else{
            throw new \yii\web\BadRequestHttpException('containerGuid error.');
        }

        if (!$this->contentContainer->permissionManager->can(new \humhub\modules\post\permissions\CreatePost())) {
            Yii::$app->params['res-success'] = false;
            return false;
        }

        //check space type
        if( $this->contentContainer->s_type != Yii::$app->params['stype_task'] ){
            throw new \yii\web\BadRequestHttpException('s_type error.');
        }

        $post = new Post();
        $post->scenario = 'task';
        $post->message = \Yii::$app->request->post('message');
        $post->p_type  = $p_type;
        $post->p_title = \Yii::$app->request->post('p_title');
        $post->p_team  = (int)\Yii::$app->request->post('p_team');
        $post->p_score = (int)\Yii::$app->request->post('p_score');
        $post->p_video = \Yii::$app->request->post('p_video');
        $post->p_secs  = (int)\Yii::$app->request->post('p_secs');
        $post->ry_did = \Yii::$app->request->post('ry_did');
        return \humhub\modules\content\widgets\WallCreateContentForm::create($post, $this->contentContainer);
    }

    /**
     * 编辑子任务
     *
     * PUT /api/task
     *
     * post.id 子任务的id，在子任务列表里可以取到
     *
     * 其他参数同接口:发布子任务
     *
     * @return boolean
     */
    public function actionEdit(){
        $id = Yii::$app->request->post('id');
        $edited = false;

        $model = Post::findOne(['id' => $id]);
        if( ! $model ){
            throw new \yii\web\BadRequestHttpException('Task not found.');
        }
        if( (time() - strtotime($model->created_at)) > 600 ){
            throw new \yii\web\BadRequestHttpException('任务不能编辑.');
        }
        $model->scenario = 'task';

        //check type=task
        if( $model->p_type != Yii::$app->params['ptype_task'] ){
            throw new \yii\web\BadRequestHttpException('task type error.');
        }

        if (!$model->content->canWrite()) {
            throw new \yii\web\BadRequestHttpException('Access denied!');
        }

        if ($model->load( ['Post'=>Yii::$app->request->post()] )) {
            // Reload record to get populated updated_at field
            if($model->validate() && $model->save()) {
                //处理fileList
                $files = explode(',', Yii::$app->request->post('fileList'));
                if( $files[0] ){
                    $_file = \humhub\modules\file\models\File::findOne(['guid' => $files[0]]);
                    if( $_file && $_file->created_by==Yii::$app->user->id ){
                        $_file->object_model = Post::className();
                        $_file->object_id = $model->id;
                        $_file->save();
                    }
                }
                return array(
                    'postId' => $id,
                );
                return true;
            }
        }
        Yii::$app->params['res-success'] = false;
        return false;
    }

    /**
     * 获取指定任务的子任务列表(space.post)
     *
     * GET api/task/stream?s=[:guid]&limit=[4]&filters=&sort=c&from=[66]&mode=normal
     *
     * get.s : 任务Space的guid
     *
     * get.limit : 单次获取总量
     *
     * get.from : 起始wallEntryID，默认为空''=第一页
     *
     * @return array  output:返回的内容, counter:表示获取几个wallEntry,  entryIds:表示所有返回的wallEntryID, lastEntryId:列表中最后一个EntryId (其中outpu中的space的p_team=1说明其是团队任务，=0则为个人任务)
     */
    public function actionStream(){
        if($this->contentContainer->s_type != 1){
            throw new \yii\web\BadRequestHttpException('任务未找到.');
        }
        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        return $stream->run();
    }

    /**
     * 获取主任务详情
     *
     * GET /api/task?s=[sguid]
     *
     * get.sguid 主任务的sguid (space的sguid)
     *
     * 任务状态的判断：参考api/directory/stream文档, 距离报名报名截止时间可使用接口中times和s_t1计算，如果报名时间已过，则倒计时消失, 此版本不用做动态倒计时！
     * - 按钮状态面板：发布者
     * - 按钮状态面板：普通用户-未报名：
     * - 按钮状态面板：普通用户-已报名
     *
     * @return 返回参数参考发布子任务接口; 如果子任务是团队任务, 则会额外返回部分团队成员信息(usercount是参与用户总数, leader=1说明这个用户是组长，通常会在用户列表第一个位置, ismember=1说明自己已参与任务,新增space里面特殊任务标记 s_special)
     * - 新增jobboard 排行榜链接
     */
    public function actionInfo(){
        $space = $this->contentContainer;
        if( $space->s_type != 1 ){
            throw new \yii\web\BadRequestHttpException('任务未找到.');
        }
        $id = $space->id;
        $arr=['3d4eea55-b999-4faa-a3b6-af8d778bb95a','28c0ab00-ef0c-4a6b-9b44-72785c49bbd8','b805c058-3c9e-4bcf-9503-d5deec0d450c','1d5ff9ea-2fb0-4f81-9671-91c4382224a0'];

        $s = [];
        $s['name'] = $space->name;
        $s['guid'] = $space->guid;
        if (in_array($s['guid'],$arr)){
            $s['special']=1;
        }else{
            $s['special']=0;
        }
        //Task
        $s['tags']   = \humhub\widgets\RichText::widget(['text' => $space->tags, 'record' => $space]);
        $s['s_type'] = $space->s_type;
        $s['s_t1']   = $space->s_t1;
        $s['s_t2']   = $space->s_t2;
        //$s['s_img']  = $space->s_img;
        $s['s_img']  = '';
        $s['s_imgguid']  = $space->s_img;
        $_file = \humhub\modules\file\models\File::findOne(['guid' => $space->s_img]);
        if( $_file ){
            if ($_file->getMimeBaseType() == "image"){
                $s['s_img']  = $_file->getPreviewImageUrl(200, 200);
            }
        }
        //+more
        $s['description'] = $space->description;
        $s['join_policy'] = $space->join_policy;
        $s['visibility']  = $space->visibility;
        $s['created_at']  = $space->created_at;
        $s['created_by']  = $space->created_by;
        $s['updated_at']  = $space->updated_at;
        $s['updated_by']  = $space->updated_by;
        $s['s_mode']      = $space->s_mode;
        $s['s_achi']      = $space->s_achi;
        $s['s_pg']        = $space->s_pg;
        $s['s_score']     = $space->s_score;
        $s["ry_did"]      = $space->ry_did;
        $s["s_special"]      = $space->s_special;
        //Task Users
//        $tcount= TaskUser::find()->where(['space_id'=>$space->id])->count();
//        $s['usercount'] = $tcount;
        $s['users']  = Array();

//        $tuser = TaskUser::find()->select(['leader', 'user_id',])->where(['space_id'=>$space->id])
//            ->with('user')->orderBy('leader DESC')->limit(6)->all();
//        foreach($tuser AS $one){
//             $u['user_id']      = $one->user_id;
//             $u['leader']       = $one->leader;
//             $u['guid']         = $one->user->guid;
//             $u['username']     = $one->user->username;
//             $u['profileimage'] = $one->user->getProfileImage()->getUrl();
//             $u['displayname']  = $one->user->displayName;
//             $s['users'][] = $u;
//        }
        //Task Users  参加任务统计
        $members=Membership::getSpaceMembersQuery($space);
        $tcount=$members->count();
        $s['usercount'] = $tcount-1;
        $tuser=$members->andWhere(['group_id'=>'member'])->limit(6)->all();
        foreach($tuser AS $one){
            $u['user_id']      = $one->id;
//            $u['leader']       = $one->leader;
            $u['guid']         = $one->guid;
            $u['username']     = $one->username;
            $u['profileimage'] = $one->getProfileImage()->getUrl();
            $u['displayname']  = $one->displayName;
            $s['users'][] = $u;
        }

        $stream = Yii::createObject([
            'class' => \humhub\modules\api\cccstream\ContentContainerStream::className(),
            'contentContainer' => $this->contentContainer
        ], ['stream', $this]);
        $posts = $stream->run();
        $post_id = 0;
        $post_t  = 0;
        foreach($posts['output'] AS $post){
            if( $post_id == 0 ){
                $post_id = $post['object']['id'];
                $post_t  = strtotime($post['object']['created_at']);
            }else{
                if( strtotime($post['object']['created_at']) < $post_t ){
                    $post_id = $post['object']['id'];
                    $post_t  = strtotime($post['object']['created_at']);
                }elseif( strtotime($post['object']['created_at']) == $post_t ){
                    if( $post['object']['id'] < $post_id ){
                        $post_id = $post['object']['id'];
                        $post_t  = strtotime($post['object']['created_at']);
                    }
                }
            }
        }
        //子任务详情
        $model = Post::findOne(['id' => $post_id]);
        if( ! $model ){
            throw new \yii\web\BadRequestHttpException('Task not found.');
        }

        $job = [];
        //$job['post']  = $model;
        $job['post']["id"]         = $model->id;
        $job['post']["message"]    = $model->message;
        $job['post']["created_at"] = $model->created_at;
        $job['post']["created_by"] = $model->created_by;
        $job['post']["updated_at"] = $model->updated_at;
        $job['post']["updated_by"] = $model->updated_by;
        $job['post']["p_type"]     = $model->p_type;
        $job['post']["p_postid"]   = $model->p_postid;
        $job['post']["p_teachers"] = $model->p_teachers;
        $job['post']["p_video"]    = '';
        $job['post']["p_videoguid"]= $model->p_video;
        $job['post']["p_secs"]     = $model->p_secs;
        $job['post']["p_title"]    = $model->p_title;
        $job['post']["p_team"]     = $model->p_team;
        $job['post']["p_score"]    = $model->p_score;
        $job['post']["ry_did"]     = $model->ry_did;
        if( $model->p_video ){
            $_file = \humhub\modules\file\models\File::findOne(['guid' => $model->p_video]);
            if( $_file ){
                $job['post']["p_video"] = $_file->getUrl();
            }
        }

        //Files
        $files = \humhub\modules\file\models\File::getFilesOfObject($model);
        $job['image'] = [];
        foreach ($files as $file){
            if ($file->getMimeBaseType() == "image"){
                $job['image'][] = $file->getPreviewImageUrl(200, 200);
            }
        }
        $job['files'] = [];
        foreach ($files as $file){
            if ($file->getMimeBaseType() == "image")
                continue;
            $f['url'] = $file->getUrl();
            $f['name'] = $file->file_name;
            $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
            $job['files'][] = $f;
        }

        $job['join']  = 0;
        $my = TaskUser::findOne(['task_id'=>$post_id, 'user_id'=>Yii::$app->user->id]);
        if( $my ){
            $job['join'] = 1;
        }
        //------------------

        $_user= User::findOne(['id' => $space->created_by]);
        $user['guid']  = $_user->guid;
        $user['image'] = $_user->getProfileImage()->getUrl();
        $user['displayname'] = $_user->displayName;
        $user['title'] = $_user->profile->title;
        $user['u_v']   = $_user->u_v;

        $o['user']  = $user;
        $o['job']   = $job;
        $o['space'] = $s;
        $o['ismember'] = 0;
        $o['times'] = time();
        if ($space->isMember()) {
            $o['ismember'] = 1;
        }

        $o['jobboard'] = 'http://www.uni-class.com/jobs/board/'.$post_id;

        return $o;
    }

    /**
     * 获取子任务详情
     *
     * GET /api/task/[id]?s=[sguid]
     *
     * get.id 子任务的id（post.id)
     *
     * get.sguid 任务所属主任务的sguid (space的sguid)
     *
     * @return 返回参数参考发布子任务接口; 如果子任务是团队任务, 则会额外返回部分团队成员信息(usercount是参与用户总数, leader=1说明这个用户是组长，通常会在用户列表第一个位置, join=1说明自己已参与任务)
     */
    public function actionView($id){
        $model = Post::findOne(['id' => $id]);
        if( ! $model ){
            throw new \yii\web\BadRequestHttpException('Task not found.');
        }

        //$o['post']  = $model;
        $o['post']["id"]         = $model->id;
        $o['post']["message"]    = $model->message;
        $o['post']["created_at"] = $model->created_at;
        $o['post']["created_by"] = $model->created_by;
        $o['post']["updated_at"] = $model->updated_at;
        $o['post']["updated_by"] = $model->updated_by;
        $o['post']["p_type"]     = $model->p_type;
        $o['post']["p_postid"]   = $model->p_postid;
        $o['post']["p_teachers"] = $model->p_teachers;
        $o['post']["p_video"]    = '';
        $o['post']["p_videoguid"]= $model->p_video;
        $o['post']["p_secs"]     = $model->p_secs;
        $o['post']["p_title"]    = $model->p_title;
        $o['post']["p_team"]     = $model->p_team;
        $o['post']["p_score"]    = $model->p_score;
        $o['post']["ry_did"]     = $model->ry_did;
        if( $model->p_video ){
            $_file = \humhub\modules\file\models\File::findOne(['guid' => $model->p_video]);
            if( $_file ){
                $o['post']["p_video"] = $_file->getUrl();
            }
        }

        $o['users'] = array();
        //if( $model->p_team==1 ){
            $tcount= TaskUser::find()->where(['task_id'=>$id])->count();
            $o['usercount'] = $tcount;
            $tuser = TaskUser::find()->select(['leader', 'user_id',])->where(['task_id'=>$id])
                ->with('user')->orderBy('leader DESC')->limit(6)->all();
            foreach($tuser AS $one){
                $u['user_id'] = $one->user_id;
                $u['leader']  = $one->leader;
                $u['guid']    = $one->user->guid;
                $u['username']= $one->user->username;
                $u['profileimage'] = $one->user->getProfileImage()->getUrl();
                $u['displayname']  = $one->user->displayName;
                $o['users'][] = $u;
            }
        //}

        //Files
        $files = \humhub\modules\file\models\File::getFilesOfObject($model);
        $o['image'] = [];
        foreach ($files as $file){
            if ($file->getMimeBaseType() == "image"){
                $o['image'][] = $file->getPreviewImageUrl(200, 200);
            }
        }
        $o['files'] = [];
        foreach ($files as $file){
            if ($file->getMimeBaseType() == "image")
                continue;
            $f['url'] = $file->getUrl();
            $f['name'] = $file->file_name;
            $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
            $o['files'][] = $f;
        }

        $o['join']  = 0;
        $my = TaskUser::findOne(['task_id'=>$id, 'user_id'=>Yii::$app->user->id]);
        if( $my ){
            $o['join'] = 1;
        }

        return $o;
    }

    /**
     * 获取主(子)任务的参与者列表
     *
     * GET /api/task/users/[id]?s=[sguid]
     *
     * GET /api/task/users?s=[sguid]
     *
     * get.id 如果设置此参数，则返回对应子任务的用户列表，否则返回主任务的用户列表
     *
     * get.sguid 主任务的sguid (space的sguid)
     *
     * @return 返回用户列表; 如果获取的子任务是团队任务, 则leader=1说明这个用户是组长，通常会在用户列表第一个位置(count是参与用户总数, follow:当前可以关注的操作,值=follow表示可以关注,=unfollow表示可以取消关注,=''无操作)
     */
    public function actionUsers($id=0){
        if( $id ){
            //子任务
            $model = Post::findOne(['id' => $id]);
            if( ! $model ){
                throw new \yii\web\BadRequestHttpException('Task not found.');
            }

            $o['users'] = array();
            if( $model->p_team==1 ){
                $tcount= TaskUser::find()->where(['task_id'=>$id])->count();
                $o['count'] = $tcount;
//                $pagination = new \yii\data\Pagination(['totalCount' => $tcount,'validatePage' => false,'defaultPageSize' => 20]);
                $pagination = new \yii\data\Pagination([
                    'defaultPageSize' => 10,
                    'validatePage' => false,
                ]);
                $tuser = TaskUser::find()->select(['leader', 'user_id',])->where(['task_id'=>$id])
                    ->with('user')->orderBy('leader DESC')
                    ->offset($pagination->offset)->limit($pagination->limit)
                    ->all();
                foreach($tuser AS $one){
                    $u['user_id'] = $one->user_id;
                    $u['leader']  = $one->leader;
                    $u['guid']    = $one->user->guid;
                    $u['username']= $one->user->username;
                    $u['profileimage'] = $one->user->getProfileImage()->getUrl();
                    $u['displayname']  = $one->user->displayName;
                    $u['follow'] = \humhub\modules\api\models\Follow::getFollow($one->user);
                    $u['countFollowers'] = $one->user->getFollowerCount(); //被关注
                    $u['title'] = $one->user->profile->title;
                    $o['users'][] = $u;
                }
            }

        }else{
            //主任务
            $space = $this->contentContainer;
            if( ! $space->id ){
                throw new \yii\web\BadRequestHttpException('Task not found.');
            }
            $id = $space->id;

            $o['users'] = array();
//            $tcount= TaskUser::find()->where(['space_id'=>$id])->count();
//            $o['count'] = $tcount;
//            $pagination = new \yii\data\Pagination(['totalCount' => $tcount, 'pageSize' => 20]);
            $pagination = new \yii\data\Pagination([
                'defaultPageSize' => 10,
                'validatePage' => false,
            ]);

//            $tuser = TaskUser::find()->select(['leader', 'user_id',])->where(['space_id'=>$id])
//                ->with('user')->orderBy('leader DESC')
//                ->offset($pagination->offset)->limit($pagination->limit)
//                ->all();
//            foreach($tuser AS $one){
//                $u['user_id'] = $one->user_id;
//                $u['leader']  = $one->leader;
//                $u['guid']    = $one->user->guid;
//                $u['username']= $one->user->username;
//                $u['profileimage'] = $one->user->getProfileImage()->getUrl();
//                $u['displayname']  = $one->user->displayName;
//                $u['follow'] = \humhub\modules\api\models\Follow::getFollow($one->user);
//                $u['countFollowers'] = $one->user->getFollowerCount(); //被关注
//                $u['title'] = $one->user->profile->title;
//                $o['users'][] = $u;
//            }

            //Task Users  参加任务统计
            $members=Membership::getSpaceMembersQuery($space);
            $tcount=$members->count();
            $o['count'] = $tcount-1;
            $tuser=$members->andWhere(['group_id'=>'member'])->offset($pagination->offset)->limit($pagination->limit)->all();
            foreach($tuser AS $one){
                $u['user_id'] = $one->id;
//                $u['leader']  = $one->leader;
                $u['guid']    = $one->guid;
                $u['username']= $one->username;
                $u['profileimage'] = $one->getProfileImage()->getUrl();
                $u['displayname']  = $one->displayName;
                $u['follow'] = \humhub\modules\api\models\Follow::getFollow($one);
                $u['countFollowers'] = $one->getFollowerCount(); //被关注
                $u['title'] = $one->profile->title;
                $o['users'][] = $u;
            }
        }
        return $o;
    }

    /**
     * 设置一个组长
     *
     * PUT /api/task/team?s=[:guid]
     *
     * get.s : 任务Space的guid
     *
     * post.taskid 要设置的子任务id
     *
     * post.leader 要设置的用户uid
     */
    public function actionTeam(){
        $id = (int)Yii::$app->request->post('taskid');
        $model = Post::findOne(['id' => $id]);
        if( ! $model ){
            throw new \yii\web\BadRequestHttpException('Task not found.');
        }

        $leaderUid = (int)Yii::$app->request->post('leader');
        if( ! $leaderUid ){
            throw new \yii\web\BadRequestHttpException('User not found.');
        }

        if( $model->p_team==1 ){
            $leader = TaskUser::findOne(['task_id'=>$id, 'user_id'=>$leaderUid]);
            if( $leader ){
                //update unset
                $up = TaskUser::updateAll(['leader'=>0], ['task_id'=>$id, 'leader'=>1]);
                //update set
                $up = TaskUser::updateAll(['leader'=>1], ['task_id'=>$id, 'user_id'=>$leaderUid]);
                return $up?true:false;
            }
        }
        Yii::$app->params['res-success'] = false;
        return false;
    }
    /**
     * 删除任务
     *
     * POST /api/taskController/delete
     *
     * post.id             要删除任务的ID
     *
     * post.model          固定值[=post]
     *
     * @return array pk:任务对应ID
     */
    public function actionDelete(){
        if( Yii::$app->request->post('model') == 'post' ){
            $_GET['model'] = 'humhub\modules\post\models\Post';
        }else{
            Yii::$app->params['res-success'] = false;
            return false;
        }
        Yii::$app->response->format = 'json';

        $this->forcePostRequest();
        $json = [
            'success' => 'false'
        ];

        $model = Yii::$app->request->get('model');
        $id = (int) Yii::$app->request->post('id');

        $contentObj = Content::get($model, $id);

        if ($contentObj !== null && $contentObj->content->canEdit()) {
            if( $contentObj->created_by==Yii::$app->user->id && $contentObj->delete() ){
                return true;
            }
            /*
            $json = [
                'success' => true,
                //'uniqueId' => $contentObj->getUniqueId(),
                //'model' => $model,
                'pk' => $id
            ];
            return $json;
             */
        }
        Yii::$app->params['res-success'] = false;
        return false;
    }
}
